/*首页工具*/
let Home_Tools = {
    "o": function(s){
       return ( s ? $("#home").find(s).eq(0) : $("#home") );
     },
    "init": function(){
        //窗口关闭按钮
        this.o().find("> div > p:first-child > a:last-child").click(function(){
           $(this).parent().parent().hide();
        });

        $("#home > div").draggable({containment:"parent", handle:"p:first-child"}); //拖拽
    },
    "show": function(o){
       let dom = this.o();
       let t = parseInt(dom.data("index"));
       let title = o.find("> p:first-child > span:first-child").eq(0);
       t = isNaN(t) ? 1 : (t + 1);
       dom.data("index", t);
       o.css("z-index", t);
       o.show();

       title.off("click");
       title.click(function(){
          Home_Tools.show($(this).parent().parent());
       });
    },
    /*密码生成*/
    "create_pwd": function(o, _this){
        let dom = this.o(".create_pwd");
        if('undefined' == typeof(o)){ this.show(dom); return; }
        let obj = window.Apps.field(dom[0],['len','number','lower','upper','other','enc']);
        if(2 === o){ //复制
           obj.enc.select();
           let clipboard = App_Gui.Clipboard.get();
           clipboard.set(obj.enc.val(),'text');
           _this.style.color = 'green';
           setTimeout(function(){
              _this.style.color = '#000';
           }, 500);
          return;
        }

        let str = (obj.number[0].checked ? obj.number.val() : '')
                  + (obj.lower[0].checked ? obj.lower.val() : '')
                  + (obj.upper[0].checked ? obj.upper.val() : '')
                  + (obj.other[0].checked ? obj.other.val() : '');
        if(str){
            str = this.string_rand(str);
            let len = parseInt(obj.len.val());
            len = isNaN(len) ? 0 : len;
            if(len) obj.enc.val(randmixed(len, str));
        }
    },
    /*base64编码与解码*/
    "base64": function(o){
        let dom = this.o(".base64");
        if('undefined' == typeof(o)){ this.show(dom); return; }
        let txt = dom.find("textarea").eq(0);

        if(1 === o){ //编码
           txt.val( Enc.base64_encode(txt.val()) );
        } else if(2 === o) { //文件转base64编码
           let f = dom.find('input[type="file"]').eq(0).val();
           if(f) txt.val( Enc.file_toBase64(f) );
        } else { //解码
           let val = txt.val();
           let bs  = val.indexOf("base64,");
           if('data:' === val.substr(0,5) && bs > 0){ val = val.substr(bs + 7); }
           txt.val( Enc.base64_decode(val) );
        }
    },
    "string_rand": function(raw_str){
        let len = raw_str.length;
        let size = 0;
        let arr = ',';
        let str = '';
        while(size < len){
           let p = Math.floor(Math.random() * len);
           if(arr.indexOf(','+p+',') < 0){
             arr += p + ',';
             size++;
           }
        }
        arr = arr.substr(1, arr.length - 2).split(',');
        let txt_str = raw_str;
        $.each(arr, function(i,v){
            str += txt_str.charAt(parseInt(v));
        });

        return str;
    },
    /*字符串随机排序*/
    "string_sort": function(o){
        let dom = this.o(".string_sort");
        if('undefined' == typeof(o)){ this.show(dom); return; }
        let txt = dom.find("textarea").eq(0);

        txt.val( this.string_rand(txt.val()) );
    },
    /*URI编码*/
    "uri_encode": function(o){
        let dom = this.o(".uri_encode");
        if('undefined' == typeof(o)){ this.show(dom); return; }

        let txt = dom.find("textarea").eq(0);
        txt.val(o ? encodeURIComponent(txt.val()) : decodeURIComponent(txt.val()));
    },
    /*大小写转换*/
    "upper_low": function(o){
        let dom = this.o(".upper_low");
        if('undefined' == typeof(o)){ this.show(dom); return; }

        let txt = dom.find("textarea").eq(0);
        txt.val(o ? txt.val().toUpperCase() : txt.val().toLowerCase());
    },
    /*hash校验*/
    "hash_encode": function(o){
        let dom = this.o(".hash_encode");
        if('undefined' == typeof(o)){ this.show(dom); return; }
        let obj = window.Apps.field(dom[0],['md5','sha256','sha512','path']);
        let radio = dom.find('.input_list > p:last-child > label > input[type="radio"]');
        let upper = radio[0].checked ? radio.eq(0).val() : radio.eq(1).val();
        obj.txt = dom.find('textarea');

        if(2 === o){
            obj.txt.val('');
            Enc.file_verify(obj.path.val(), function(hash){
               Object.keys(hash).forEach(function(k){
                  obj[k].val('upper' === upper ? hash[k].toUpperCase() : hash[k].toLowerCase());
               });
            });
        } else {
            let txt = obj.txt.val();
            if(!txt) return;
            let ens = '';
            obj.path.val('');

            ens = Enc.md5(txt);
            obj.md5.val('upper' === upper ? ens.toUpperCase() : ens.toLowerCase());

            ens = Enc.sha(txt,'256');
            obj.sha256.val('upper' === upper ? ens.toUpperCase() : ens.toLowerCase());

            ens = Enc.sha(txt,'512');
            obj.sha512.val('upper' === upper ? ens.toUpperCase() : ens.toLowerCase());
        }

        radio.off("change");
        radio.change(function(){
           if(this.checked){
               let items = window.Apps.field($(this).parent().parent().parent().parent()[0],['md5','sha256','sha512']);
               if("upper" == this.value){
                  $.each(items, function(i,v){ v.val(v.val().toUpperCase()); });
               } else {
                  $.each(items, function(i,v){ v.val(v.val().toLowerCase()); });
               }
           }
        });

    },
    /*时间戳转换*/
    "unixtime": function(o){
        let dom = this.o(".unixtime");
        let obj = window.Apps.field(dom[0],['ntime','ltime','temptime']);
        this.show(dom);

        obj.ntime.off("click");
        obj.ntime.click(function(){
           let t = parseInt(new Date().valueOf()/1000);
           $(this).val(t);
           $(this).parent().find("input:last-child").val(UnixToDateTime(t));
        });
        obj.ntime.click();

        //let ltime = dom.find('input[name="ltime"]').eq(0);
        obj.ltime.off("change");
        obj.ltime.change(function(){
           let t = parseInt(new Date(this.value).valueOf()/1000);
           $(this).parent().find("input:last-child").val(t);
        });

        //let temptime = dom.find('input[name="temptime"]').eq(0);
        obj.temptime.off("change");
        obj.temptime.change(function(){
           let t = parseInt(this.value);
           t = isNaN(t) ? 0 : t;
           $(this).parent().find("input:last-child").val(UnixToDateTime(t));
        });
    },
    "utf16to8": function(){
          var out, i, len, c;
          out = "";
          len = str.length;
          for (i = 0; i < len; i++) {
            c = str.charCodeAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
              out += str.charAt(i);
            } else if (c > 0x07FF) {
              out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
              out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
              out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            } else {
              out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
              out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
            }
          }
          return out;
    },
    /*二维码生成*/
    "qrcode": {
      "o": function(){return Home_Tools.o(".qrcode");},
      "show": function(){
          let dom = this.o();
          let file = dom.find("input[type=file]").eq(0);
          let qr_dom = this.o().find("> .input_list > div:last-child").eq(0);
          file.off("change");
          file.change(function(){
             let obj = $(this).parent().parent().find("> textarea[name=content]");
             if( Fs.existsSync(this.files[0].path) ){
                 let qr_bast64 = Enc.file_toBase64(this.files[0].path);
                 qr_dom.html('<img src="'+qr_bast64+'" style="width:230px;"/>');
                 qrcode.decode(window.webkitURL.createObjectURL(this.files[0]));
                 qrcode.callback = function(msg){ obj.val(msg); }
             } else {
                 Public_Object.tip("二维码文件不存在!");
             }
          });
          Home_Tools.show(dom);
      },
      "create": function(o){
          let qr_dom = this.o().find("> .input_list > div:last-child").eq(0);
          let str = this.o().find("textarea[name='content']").val();
           //console.log(str);
          qr_dom.html("");
          qr_dom.qrcode({
              render: 'image',  // 渲染模式 canvas, image, table
              correctLevel:0,
              size: 230,  // 大小
              background: '#fff',  // 背景颜色
              text: str
          });
      },
      "decode": function(o){
        $(o).parent().find('input').click();
      }
    },
    /*字符串去重*/
    "unique": {
      "o": function(){return Home_Tools.o(".unique");},
      "field": function(n,t){
         return Apps.field(this.o().get(0), n, t);
      },
      "show": function(){;
          let obj = this.field(["active","r_input","t_input"]);
          Home_Tools.show(this.o());

          obj.active.off("change");
          obj.active.change(function(){
            let val = parseInt(this.value);
            if(6 == val || 7 == val){
              obj.r_input.width(300);
              obj.t_input.show();
            } else {
              obj.t_input.hide();
              obj.r_input.width(500);
            }
          });
      },
      "go": function(){
          let obj = this.field(["active","t_text"]);
          obj.t_text.val("");
          switch(parseInt(obj.active.val())){
            case 1: this.uniq(); break; // 去除重复
            case 2: this.del_text(); break;// 去除内容
            case 3: this.del_empty_line(); break;// 去掉空行
            case 4: this.del_text_line(); break;// 去掉行包含
            case 5: this.stay_text_line(); break;// 保留行包含
            case 6: this.replace_text(); break;// 内容替换
            case 7: break;// 替换行包含
            case 8: this.add_text_on_start(); break;// 添加到行首
            case 9: this.add_text_on_end(); break;// 添加到行尾
            case 10: this.del_ch_word(); break;
            case 11: this.del_en_word(); break;// 去掉英文字母
            case 12: this.del_number(); break;
            case 13: this.del_dom(); break;// 去掉html标记
          }
      },
      // 去掉重复行
      "uniq": function(){
          let obj = this.field(["t_text","r_text"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n");
          let tmpstr = '';
          for(let i = 0; i < strs.length; i++){
             if( ("\n" + tmpstr).indexOf("\n" + strs[i] + "\n") < 0 ) tmpstr += strs[i] + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 去除指定内容
      "del_text": function(){
          let obj = this.field(["t_text","r_text","r_input"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n"), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
             tmpstr += strs[i].replace(obj.r_input.val(),"") + "\n";
          }
          obj.t_text.val(tmpstr);
       },
       // 去除空行
      "del_empty_line": function(){
          let obj = this.field(["t_text","r_text"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n"), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs[i].length > 0 ) tmpstr += strs[i] + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 去掉包含指定内容的行
      "del_text_line": function(){
          let obj = this.field(["t_text","r_text","r_input"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n"), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( -1 == strs[i].indexOf(obj.r_input.val()) ) tmpstr += strs[i] + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 保留行包含指定内容的行
      "stay_text_line": function(){
          let obj = this.field(["t_text","r_text","r_input"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n");
          let tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs[i].indexOf(obj.r_input.val()) > -1 ) tmpstr += strs[i] + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 替换内容
      "replace_text": function(){
          let obj = this.field(["t_text","r_text","r_input","t_input"]);
          obj.t_text.val( obj.r_text.val.replace(new RegExp(obj.r_input.val(),"gm"), obj.t_input.val()) );
      },
      // 添加指定内容到行首
      "add_text_on_start": function(){
          let obj = this.field(["t_text","r_text","r_input"]);
          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n"), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs[i].length > 0 ) tmpstr += obj.r_input.val() + strs[i] + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 添加指定内容到行尾
      "add_text_on_end": function(){
          let obj = this.field(["t_text","r_text","r_input"]);

          let strs = obj.r_text.val().replace(/\\r\\n/g, "\n").replace(/\\r/g, "\n").split("\n"), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs[i].length > 0 ) tmpstr += strs[i] + obj.r_input.val() + "\n";
          }
          obj.t_text.val(tmpstr);
      },
      // 去掉中文字符
      "del_ch_word": function(){
          let obj = this.field(["t_text","r_text"]);

          let strs = obj.r_text.val(), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs.charCodeAt(i) > 0 && strs.charCodeAt(i) < 256 ) tmpstr += strs.charAt(i);
          }
          obj.t_text.val(tmpstr);
      },
      // 去掉英文字母
      "del_en_word": function(){
          let obj = this.field(["t_text","r_text"]);

          let strs = obj.r_text.val(), tmpstr = '';
          for(let i = 0; i < strs.length; i++){
            if( strs.charCodeAt(i) < 65 || strs.charCodeAt(i) > 90 ){
              if(strs.charCodeAt(i) < 97 || strs.charCodeAt(i) > 122) tmpstr += strs.charAt(i);
            }
          }
          obj.t_text.val(tmpstr);
      },
      // 去掉数字
      "del_number": function(){
          let obj = this.field(["t_text","r_text"]);

          let strs = obj.r_text.val(), tmpstr = "";
          for(let i = 0; i < strs.length; i++){
            if( strs.charCodeAt(i) < 48 || strs.charCodeAt(i) > 57 ) tmpstr += strs.charAt(i);
          }
          obj.t_text.val(tmpstr);
      },
      // 去掉html标记
      "del_dom": function(){
          let obj = this.field(["t_text","r_text"]);
          let strs = obj.r_text.val();
          obj.t_text.val(strs.replace(/<[^>]*>/g,''));
      }
    },
    //JSON格式化
    "json_style":{
       "style": function(json){
            if (typeof json != 'string') json = JSON.stringify(json, undefined, 2);

            json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                  var cls = 'number';
                  if (/^"/.test(match)) {
                      if (/:$/.test(match)) {
                          cls = 'key';
                      } else {
                          cls = 'string';
                      }
                  } else if (/true|false/.test(match)) {
                      cls = 'boolean';
                  } else if (/null/.test(match)) {
                      cls = 'null';
                  }
                  return '<span class="' + cls + '">' + match + '</span>';
            });
       },
       "go": function(){
          let dom = Home_Tools.o(".json_style");
          let txt = Apps.field(dom[0], "txt");
          Home_Tools.show(dom);

          txt.off("click");
          txt.click(function(){
            if(!$(this).hasClass('active')){ $(this).addClass('active'); this.readOnly=false; }
          });

          txt.off("dblclick");
          txt.dblclick(function(){
            $(this).removeClass('active');
            this.readOnly=true;

            let p = $('<pre><a onclick="$(this).parent().remove();">x</a></pre>');
            let view = $(this).parent().find(".json_info").eq(0);
            let val = this.value.replace(/\n|\r/g,"")
                      .replace(/\{"/g,'{\n   "')
                      .replace(/\"}/g,'"\n}')
                      .replace(/","/g,'",\n   "');
            p.append(Home_Tools.json_style.style(val));
            view.append(p);

          });
       }
    },
    //查询ip地址信息
    "get_ip_info":function(o){
          let dom = Home_Tools.o(".get_ip_info");
          let ip = Apps.field(dom[0], "ip");
          ip.off("keydown");
          ip.keydown(function(e){
              if(13 === e.keyCode) Home_Tools.get_ip_info(1);
          });
          if('undefined' == typeof(o)){ Home_Tools.show(dom); return; }
          let txt = dom.find(".ip_info").eq(0);
          let info = '';

          if(ip.val()){
              info = Public_Object.get_data(SYS_CONF.ip_check_api.replace('{$ip}',ip.val()));
          }

          let p = $('<pre></pre>');
          p.html(Home_Tools.json_style.style(info));
          txt.append(p);
          ip.val('');
     },
     //图像识别
     "ocr":{
        "show": function(){
          let dom = Home_Tools.o(".ocr_word");
          let file = dom.find("input[type=file]").eq(0);
          file.off("change");
          file.change(function(){
             let obj = $(this).parent().parent().find("> textarea.word_info");
             if( Fs.existsSync(this.files[0].path) ){
                 //let qr_bast64 = Enc.file_toBase64(this.files[0].path);
                 let d = Baidu_Api.word(this.files[0].path);
                 let w = Public_Object.get_data(d.url, d.data,"POST");
                 if(w.words_result){
                    let msg = "";
                    $.each(w.words_result, function(i, v){ msg += v.words + "\n"; });
                    obj.val(msg);
                 } else { console.log(JSON.stringify(w)); }

             } else {
                 Public_Object.tip("文件不存在!");
             }
          });
          Home_Tools.show(dom);
        },
        "go": function(o){
          $(o).parent().find('input').click();
        }
     }
};
